package com.qqt.csr.message.event.intrasite;

import com.qqt.csr.message.entity.MessageNotify;
import com.qqt.csr.message.service.MessageNotifyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: yang hao
 * @Date: 2024/12/11 11:09
 * @Description: 站内信监听器
 **/
@Slf4j
@Component
public class IntraSiteMessageListener implements ApplicationListener<IntraSiteMessageEvent<?>> {

    /**
     * 站内信服务
     */
    private final MessageNotifyService messageNotifyService;

    /**
     * 构造函数
     * @param messageNotifyService {@link MessageNotifyService} 站内信服务
     */
    public IntraSiteMessageListener(MessageNotifyService messageNotifyService) {
        this.messageNotifyService = messageNotifyService;
    }

    /**
     * 处理站内信事件
     * @param event {@link IntraSiteMessageEvent>} 站内信事件
     */
    @Override
    public void onApplicationEvent(@NonNull IntraSiteMessageEvent<?> event) {
        try {
            log.debug("处理站内信事件，事件源: {}", event.getSource());
            List<MessageNotify> messages = event.message();
            if (messages.isEmpty()) {
                log.debug("没有获取到站内信，事件源: {}", event.getSource());
                return;
            }
            log.debug("获取到 {} 条站内信", messages.size());

            // 批量插入站内信
            messageNotifyService.saveBatch(messages);
        } catch (Exception e) {
            log.error("处理站内信事件时发生错误: {}", e.getMessage(), e);
        }
    }
}
